// 豆瓣搜索后端服务脚本
// 注意：这是一个独立的Node.js服务，需要单独运行
const express = require('express');
const axios = require('axios');
const cors = require('cors');
const { JSDOM } = require('jsdom');
const app = express();
const PORT = 3001;

// 启用CORS
app.use(cors());
// 解析JSON请求体
app.use(express.json());

// 豆瓣搜索API端点
app.get('/api/douban/search', async (req, res) => {
  try {
    const { query, q } = req.query;
    const searchQuery = q || query; // 兼容新旧参数名
    
    if (!searchQuery) {
      return res.status(400).json({ success: false, message: '搜索关键词不能为空' });
    }
    
    // 旧的实现方式 - 已注释保留
    // const searchUrl = `https://search.douban.com/movie/subject_search?search_text=${encodeURIComponent(query)}&cat=1002&sort=score`;
    // 
    // // 设置请求头，模拟浏览器请求
    // const headers = {
    //   'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36',
    //   'Cookie': 'bid=DEV0FOe_fVk; ll="108296"; ap_v=0,6.0; dbcl2="231569352:B0mtm7Sgaqk"; ck=Tg5X; push_noty_num=0; push_doumail_num=0; frodotk_db="1281e4474455f9433785acd5cd01ebc9"',
    //   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
    //   'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
    //   'Accept-Encoding': 'gzip, deflate, br',
    //   'Connection': 'keep-alive',
    //   'Upgrade-Insecure-Requests': '1',
    //   'Sec-Fetch-Dest': 'document',
    //   'Sec-Fetch-Mode': 'navigate',
    //   'Sec-Fetch-Site': 'none',
    //   'Sec-Fetch-User': '?1'
    // };
    
    // 发起请求到豆瓣搜索
    console.log(`正在请求豆瓣搜索: ${searchUrl}`);
    const response = await axios.get(searchUrl, {
      headers,
      responseType: 'text'
    });
    
    // 解析HTML内容
    const dom = new JSDOM(response.data);
    const window = dom.window;
    const document = window.document;
    
    // 尝试从HTML中提取window.__DATA__对象
    let dataContent = null;
    const scriptElements = document.querySelectorAll('script');
    
    for (const script of scriptElements) {
      const content = script.textContent || '';
      if (content.includes('window.__DATA__')) {
        const match = content.match(/window\.__DATA__\s*=\s*(\{.*?\});/s);
        if (match) {
          dataContent = match[1];
          break;
        }
      }
    }
    
    if (!dataContent) {
      return res.status(500).json({ success: false, message: '无法从豆瓣页面获取数据' });
    }
    
    // 解析JSON数据
    let jsonData;
    try {
      jsonData = JSON.parse(dataContent);
    } catch (parseError) {
      console.error('解析JSON失败:', parseError);
      return res.status(500).json({ success: false, message: '解析数据失败' });
    }
    
    // 提取动漫数据
    const animeList = [];
    
    if (jsonData.items && Array.isArray(jsonData.items)) {
      jsonData.items.forEach((item, index) => {
        if (item.tpl_name === 'search_subject') {
          // 提取评分信息
          let rating = 0;
          if (item.rating && item.rating.value > 0) {
            rating = item.rating.value;
          }
          
          // 提取标签信息
          let status = '';
          if (item.labels && Array.isArray(item.labels)) {
            status = item.labels.map(label => label.text).join('、');
          }
          
          // 提取年份信息
          let year = 2024; // 默认年份
          const yearMatch = item.title.match(/\((\d{4})\)$/);
          if (yearMatch) {
            year = parseInt(yearMatch[1], 10);
          }
          
          // 添加到动漫列表
          animeList.push({
            id: Date.now() + index,
            doubanId: item.id.toString(),
            title: item.title.replace(/\s*\(\d{4}\)$/, ''),
            originalTitle: item.title,
            coverImageUrl: item.cover_url,
            link: item.url,
            description: item.abstract || '',
            releaseDate: year + '-01-01',
            rating: rating,
            votes: item.rating ? parseInt(item.rating.count, 10) || 0 : 0,
            year: year,
            tags: status,
            actors: item.abstract_2 || '',
            ratingStar: item.rating ? item.rating.star_count : 0
          });
        }
      });
    }
    
    // 过滤结果，只保留动画相关的条目
    // const filteredAnimeList = animeList.filter(anime => 
    //   anime.description && anime.description.includes('动画')
    // );
    // 注意：这段代码已被新的实现替代
    
    // 新的实现方式 - 使用豆瓣开放API
    const apiUrl = 'https://api.douban.com/v2/movie/search';
    const apiKey = '0ab215a8b1977939201640fa14c66bab';
    
    console.log(`正在请求豆瓣开放API: ${apiUrl}`);
    const apiResponse = await axios.post(apiUrl, {
      q: searchQuery,
      start: 0,
      count: 100,
      apikey: apiKey
    }, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
    // 提取返回的数据
    const apiData = apiResponse.data;
    
    // 转换API返回的数据格式为前端需要的格式
    const newAnimeList = [];
    
    if (apiData.subjects && Array.isArray(apiData.subjects)) {
      apiData.subjects.forEach((subject, index) => {
        // 提取导演信息
        let directors = '';
        if (subject.directors && Array.isArray(subject.directors)) {
          directors = subject.directors.map(dir => dir.name).join('、');
        }
        
        // 提取演员信息
        let actors = '';
        if (subject.casts && Array.isArray(subject.casts)) {
          actors = subject.casts.map(cast => cast.name).join('、');
        }
        
        // 提取类型信息
        let genres = '';
        if (subject.genres && Array.isArray(subject.genres)) {
          genres = subject.genres.join('、');
        }
        
        // 提取年份信息
        let year = 2024; // 默认年份
        if (subject.year) {
          year = parseInt(subject.year, 10) || 2024;
        }
        
        // 添加到动漫列表
        newAnimeList.push({
          id: Date.now() + index,
          doubanId: subject.id,
          title: subject.title,
          originalTitle: subject.original_title,
          coverImageUrl: subject.images?.medium || subject.images?.small || '',
          link: subject.alt,
          description: '', // API没有直接提供描述
          releaseDate: year + '-01-01',
          rating: subject.rating?.average || 0,
          votes: subject.collect_count || 0,
          year: year,
          tags: genres,
          actors: actors,
          ratingStar: Math.floor((subject.rating?.average || 0) / 2) * 10, // 转换为星星数
          genre: genres,
          director: directors
        });
      });
    }
    
    // 过滤结果，保留动画相关的条目
    const filteredAnimeList = newAnimeList.filter(anime => 
      anime.genre.includes('动画') || anime.genre.includes('动画电影')
    );
    
    // 返回解析后的数据
    res.json({
      success: true,
      data: filteredAnimeList,
      total: filteredAnimeList.length,
      originalData: apiData // 返回原始数据供调试
    });
    
  } catch (error) {
    console.error('豆瓣搜索失败:', error.message || error);
    res.status(500).json({
      success: false,
      message: '搜索失败，请稍后再试',
      error: error.message || String(error)
    });
  }
});

// 图片代理端点，用于解决防盗链问题
app.get('/api/image-proxy', async (req, res) => {
  try {
    const { url } = req.query;
    
    console.log(`收到图片代理请求，URL参数: ${url}`);
    
    if (!url) {
      console.log('错误: 图片URL为空');
      return res.status(400).json({ success: false, message: '图片URL不能为空' });
    }
    
    try {
      const urlObj = new URL(url);
      console.log(`解析URL成功，hostname: ${urlObj.hostname}`);
      console.log(`解析URL成功，origin: ${urlObj.origin}`);
      
      // 放宽域名限制，允许所有域名
      // 注意：在生产环境中应该限制域名以确保安全
      
      // 设置请求头，模拟浏览器并添加更多防盗链相关的头
      const headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36',
        'Referer': urlObj.origin,
        'Accept': 'image/avif,image/webp,image/apng,image/*,*/*;q=0.8',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Cache-Control': 'max-age=0',
        'Connection': 'keep-alive'
      };
      
      console.log(`准备请求图片: ${url}`);
      
      // 发起请求获取图片
      const response = await axios.get(url, {
        headers,
        responseType: 'arraybuffer',
        timeout: 10000 // 添加超时设置
      });
      
      console.log(`图片请求成功，状态码: ${response.status}, 数据长度: ${response.data.length}`);
      
      // 设置正确的Content-Type
      const contentType = response.headers['content-type'] || 'image/jpeg';
      console.log(`图片Content-Type: ${contentType}`);
      res.set('Content-Type', contentType);
      
      // 添加缓存控制头
      res.set('Cache-Control', 'public, max-age=31536000');
      
      // 返回图片数据
      res.send(Buffer.from(response.data));
      
    } catch (urlError) {
      console.error('URL解析错误:', urlError.message || urlError);
      return res.status(400).json({
        success: false,
        message: '无效的图片URL',
        error: urlError.message || String(urlError)
      });
    }
    
  } catch (error) {
    console.error('图片代理失败:', error.message || error);
    res.status(500).json({
      success: false,
      message: '图片加载失败',
      error: error.message || String(error)
    });
  }
});

// 根路径
app.get('/', (req, res) => {
  res.send('豆瓣搜索API服务运行中');
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`豆瓣搜索API服务运行在 http://localhost:${PORT}`);
  console.log('使用方法: http://localhost:${PORT}/api/douban/search?query=动漫名称');
});